﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using BLL;
using Entities;

namespace WindowsApp.QLTaiKhoan
{
    public partial class frmAddTaiKhoan : DevComponents.DotNetBar.Office2007Form
    {
        TaiKhoan _taikhoan;
        TaiKhoanManager _manager;
        bool _isUpdate;
        public frmAddTaiKhoan()
        {
            InitializeComponent();
        }
        public frmAddTaiKhoan(TaiKhoanManager _man, TaiKhoan _tk = null)
            : this()
        {
            _manager = _man;
            _taikhoan = _tk;
            _isUpdate = _tk != null;
        }
        private void frmAddTaiKhoan_Load(object sender, EventArgs e)
        {
            if (_isUpdate)
            {
                txtTenDangNhap.Text = _taikhoan.Username;
                txtMatKhau.Text = _taikhoan.Password;
                cbbPhanQuyen.Text = _taikhoan.PhanQuyen;
            }
            else
                cbbPhanQuyen.SelectedIndex = 0;
            txtTenDangNhap.ReadOnly = _isUpdate;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!_isUpdate) _taikhoan = new TaiKhoan();

            _taikhoan.Username = txtTenDangNhap.Text;
            _taikhoan.Password = txtMatKhau.Text;
            _taikhoan.PhanQuyen = cbbPhanQuyen.SelectedItem.ToString();
            var vResult = _manager.Validate(_taikhoan);
            if (vResult.Valid)
            {
                var aResult = _manager.InsertOrUpdate(_taikhoan);
                if (aResult.Success)
                {
                    MessageBox.Show((_isUpdate ? "Cập nhật" : "Thêm") + " thành công thông tin tài khoản", "Thông báo");
                    btnReset.PerformClick();
                }
                else
                    MessageBox.Show(aResult.GetErrorMessages());
            }
            else MessageBox.Show(vResult.ToString());
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            txtTenDangNhap.ResetText();
            txtMatKhau.ResetText();
            cbbPhanQuyen.ResetText();
            txtTenDangNhap.ReadOnly = _isUpdate = false;
            this.Text = "Thêm tài khoản";
        }
    }
}